#!/usr/bin/env python

"""Helper functions"""

import os
from log import log
from PIL import Image

def flatten_dir_list(nested_list):
    """
    Utility function to cleanup CLI --dir list.

    Takes a nested list-of-lists or a simple list and returns valid and
    normalized path names.
    """
    # collapse nested list
    flat = sum(nested_list, [])
    # normalize path and include if the actual path exists
    # TODO: log message if a path has been eliminated
    norm = [ os.path.normpath(d) for d in flat if os.path.isdir(d) ]
    return norm


def locate_by_extension(root, extension):
    """Locate all files matching supplied filename pattern in and below
    supplied root directory."""
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in files:
            if filename.endswith(extension):
                yield (path, filename)
            else:
                log.debug("Excluded file %s" % filename)


def trim_extension(filename, extension):
    """Remove the given extension and return the basename. Or return the
    filename as is if the extension does not match.
    Pretty sure there is a better way of doing this, but os.path provides
    only methods which remove up to the first occurance of a dot."""
    if filename.endswith(extension):
        return filename[:-len(extension)]
    else:
        return filename


def build_filelist(dirs, ext=('.jpg','.JPG','jpeg', 'JPEG')):
    """Walk through all given directories and accumulate matching files."""
    fl = []
    for d in dirs:
        for r, f in locate_by_extension(d, ext):
            log.debug("Found: %s" % f)
            fl.append(os.path.join(r, f))
    return fl


def create_thumbnail(imgpath, size=(128, 128)):
    try:
        img = Image.open(imgpath)
        img.thumbnail(size, Image.ANTIALIAS)
        img.save(imgpath + ".tn", "JPEG")
    except IOError:
        log.error("Can not create thumbnail for", imgpath)
